/**
 * Copyright (C) 2013-2014 the original author or authors.
 */
package com.foreveross.bsl.file.storage.tfs;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.foreveross.bsl.file.storage.FileStorage;
import com.foreveross.bsl.file.storage.FileStorageFactory;
import com.taobao.common.tfs.DefaultTfsManager;

/**
 * xxx
 *
 * @author Wangyi
 * @version v1.0
 *
 * @date 2013-9-12
 *
 */
public class TfsFileStorageFactory extends FileStorageFactory {
	
	private LinkedList<DefaultTfsManager> poolTfsManager = new LinkedList<DefaultTfsManager>();
	
	private Map<DefaultTfsManager, Integer> tfsManagerTimes = new HashMap<DefaultTfsManager, Integer>();
	
	/**
	 * 
	 */
	public TfsFileStorageFactory(String configLocation) {
		ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(configLocation);
		DefaultTfsManager tfsManager = appContext.getBean("tfsManager", DefaultTfsManager.class);
		this.poolTfsManager.add(tfsManager);
	}
	
	public TfsFileStorageFactory(){
		this("classpath:/filestorage/tfs-config.xml");
	}

	public synchronized FileStorage getFileStorage(){
		if(poolTfsManager.size() > 0){
			DefaultTfsManager tfs = poolTfsManager.poll();
			if(tfs != null){
				tfsManagerTimes.put(tfs, 1);
				return new TfsFileStorage(tfs);
			}
		}
		
		if(!tfsManagerTimes.isEmpty()){
			int r = 9999999;
			DefaultTfsManager df = tfsManagerTimes.keySet().iterator().next();
			for (Iterator<DefaultTfsManager> iterator = tfsManagerTimes.keySet().iterator(); iterator.hasNext();) {
				DefaultTfsManager obj = iterator.next();
				
				if(r > tfsManagerTimes.get(obj)){
					r = tfsManagerTimes.get(obj);
					df = obj;
				}
			}
			tfsManagerTimes.put(df,tfsManagerTimes.get(df) + 1);
			return new TfsFileStorage(df);
		}
		return null;
	}
}
